package com.ymlyj666.onlinechat.control;

import com.alibaba.fastjson.JSON;
import com.ymlyj666.onlinechat.dao.FriendShipDao;
import com.ymlyj666.onlinechat.dao.MessageDao;
import com.ymlyj666.onlinechat.dao.UserDao;
import com.ymlyj666.onlinechat.model.Message;
import com.ymlyj666.onlinechat.model.Response;
import com.ymlyj666.onlinechat.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/message.do")
public class MessageServlet extends HttpServlet {
    private MessageDao messageDao;
    private UserDao userDao;
    private FriendShipDao friendShipDao;

    @Override
    public void init() throws ServletException {
        super.init();
        messageDao = new MessageDao();
        userDao = new UserDao();
        friendShipDao = new FriendShipDao();
    }

    @Override
    public void destroy() {
        try {
            messageDao.close();
            userDao.close();
            friendShipDao.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.destroy();
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getParameter("op");
        if (op == null) {
            op = "";
        }
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");

        switch (op) {
            case "send": {
                String uidFriend = req.getParameter("uid_friend");
                String content = req.getParameter("content");
                Message message = new Message();
                message.setFromUid(currentUser.getUid());
                message.setToUid(uidFriend);
                message.setContent(content);

                messageDao.save(message);
            }
            break;
            default:
                break;
        }
        long sendTime = Long.parseLong(req.getParameter("sendTime"));
        resp.getWriter().print(JSON.toJSONString(new Response<>(messageDao.findByUidAndSendTimeGT(currentUser.getUid(), sendTime))));
    }
}
